package com.daichi.controller;

import cn.hutool.core.map.MapUtil;
import com.daichi.common.lang.Const;
import com.daichi.common.lang.Result;
import com.daichi.entity.SysUser;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;

@RestController
public class AuthController extends BaseController {

    private final DefaultKaptcha producer;

    @Autowired
    public AuthController(DefaultKaptcha producer) {
        this.producer = producer;
    }

    @GetMapping("/captcha")
    public Result captcha() throws IOException {

        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String prefix = "data:image/jpeg;base64,";

        String base64Img = prefix + encoder.encode(outputStream.toByteArray());

        outputStream.flush();
        outputStream.close();

        redisUtil.hset(Const.REDIS_CAPTCHA_KEY, key, code, 120);

        return Result.succ(MapUtil.builder().put("token", key).put("captchaImg", base64Img).build());
    }

    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal) {
        SysUser sysUser = sysUserService.getUserByName(principal.getName());
        return Result.succ(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUsername())
                .put("avatar",sysUser.getAvatar())
                .map()
        );
    }
}
